/*******************************************************************************
 *    版权信息   ： @copyright Copyright 2014-2021 chnenergy All Right Reserved
 *    作   者   ： hhz
 *    版   本   ： 1.1
 *    创建时间   ：2024/4/16
 *    最后修改日期   ： 2024/4/16
 *    最后修改人员   ： hhz
 ******************************************************************************/
package io.github.houhanzhi.hhregistry.cluster;

import io.github.houhanzhi.hhregistry.config.HHRegistryConfigProperties;
import io.github.houhanzhi.hhregistry.http.HttpInvoker;
import io.github.houhanzhi.hhregistry.service.HHRegistryService;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 集群行为 Registry Cluster
 **/
@Slf4j
public class Cluster {

    @Value("${server.port}")
    String port;

    String host;

    Server MYSELF;


    HHRegistryConfigProperties registryConfigProperties;

    public Cluster(HHRegistryConfigProperties registryConfigProperties) {
        this.registryConfigProperties = registryConfigProperties;
    }

    List<Server> servers;

   

    public void init() {

        try {
            // 此处获取的 ip 地址是宿主机地址：192.168.11.202
            host = new InetUtils(new InetUtilsProperties()).findFirstNonLoopbackHostInfo().getIpAddress();
            log.info(" ===> findFirstNonLoopbackHostInfo:{} " , host);
        } catch (Exception e) {
            host = "127.0.0.1";
        }

        MYSELF = new Server("http://" + host + ":" + port, true, false, -1L);
        log.info(" ===> myself:{}" ,MYSELF);

        initServers();
        new ServerHealth(this).checkServerHealth();
    }

    @NotNull
    private void initServers() {
        List<Server> servers = new ArrayList<>();
        log.info("init cluster");
        // 此处的ip地址是 127.0.0.1
        final List<String> serverList = registryConfigProperties.getServerList();
        for (String url : serverList) {
            final Server server = new Server();
            if (url.contains("localhost")) {
                url = url.replace("localhost", host);
            } else if (url.contains("127.0.0.1")) {
                url = url.replace("127.0.0.1", host);
            }

            if (url.equals(MYSELF.getUrl())) {
                servers.add(MYSELF);
            } else {
                server.setUrl(url);
                server.setStatus(false);
                server.setLeader(false);
                server.setVersion(-1L);
                servers.add(server);
            }
        } 
        this.servers = servers;
    }


    public Server self() {
        MYSELF.setVersion(HHRegistryService.VERSION.get());
        return MYSELF;
    }

    public List<Server> getServers() {
        return servers;
    }

    public Server leader() {
        return servers.stream()
                .filter(Server::isStatus)
                .filter(Server::isLeader)
                .findFirst()
                .orElse(null);
    }
}
